package cn.edu.sspu.www.web.exception;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.NoHandlerFoundException;

import cn.edu.sspu.www.exception.ErrorBean;
import cn.edu.sspu.www.exception.ErrorCode;

/**
 * ExceptionResolver<br>
 * 异常统一处理
 * @author warm
 * @version 2019年07月31日
 */
public class ExceptionResolver implements HandlerExceptionResolver {

    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
       
        String view = "/common/error";
        ErrorBean errorBean = new ErrorBean();
        if (ex instanceof NoHandlerFoundException) {
            String baseUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
            errorBean = ErrorBean.getErrorBean(ErrorCode.PAGE_NOT_FOUND);
            errorBean.setTrace(baseUrl + ((NoHandlerFoundException) ex).getRequestURL());
            view = "/common/404";
        } else {
        	ex.printStackTrace();
            errorBean = ErrorBean.getErrorBean(ex);
        }
        
        errorBean.setActionUrl(request.getRequestURI());
		request.setAttribute("ctx", request.getContextPath());
		
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("error", errorBean);
        modelAndView.setViewName(view);
        return modelAndView;
    }
}
